package com.studentmanagement.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.studentmanagement.model.Course;
import com.studentmanagement.model.Enrollment;
import com.studentmanagement.model.Student;
import com.studentmanagement.service.CourseService;
import com.studentmanagement.service.EnrollmentService;
import com.studentmanagement.service.StudentService;
import com.studentmanagement.util.PageBean;

@WebServlet("/enrollment/*")
public class EnrollmentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private EnrollmentService enrollmentService = new EnrollmentService();
    private StudentService studentService = new StudentService();
    private CourseService courseService = new CourseService();
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        if (pathInfo == null || pathInfo.equals("/")) {
            // 列出所有选课记录
            listEnrollments(request, response);
        } else if (pathInfo.equals("/add")) {
            // 显示添加选课表单
            showAddForm(request, response);
        } else if (pathInfo.equals("/edit")) {
            // 显示编辑选课表单
            showEditForm(request, response);
        } else if (pathInfo.equals("/delete")) {
            // 删除选课记录
            deleteEnrollment(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        if (pathInfo == null || pathInfo.equals("/")) {
            // 处理列表页面的分页请求
            listEnrollments(request, response);
        } else if (pathInfo.equals("/add")) {
            // 添加选课记录
            addEnrollment(request, response);
        } else if (pathInfo.equals("/edit")) {
            // 更新选课记录
            updateEnrollment(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    private void listEnrollments(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取分页参数
        int pageNumber = 1;
        int pageSize = 10;
        String sortField = "enrollment_id";
        String sortOrder = "ASC";
        
        try {
            if (request.getParameter("pageNumber") != null) {
                pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
            }
            
            if (request.getParameter("pageSize") != null) {
                pageSize = Integer.parseInt(request.getParameter("pageSize"));
            }
            
            if (request.getParameter("sortField") != null) {
                sortField = request.getParameter("sortField");
            }
            
            if (request.getParameter("sortOrder") != null) {
                sortOrder = request.getParameter("sortOrder");
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        
        // 获取分页数据
        PageBean<Enrollment> pageBean = enrollmentService.getEnrollmentsByPage(pageNumber, pageSize, sortField, sortOrder);
        
        // 将数据存入请求属性
        request.setAttribute("pageBean", pageBean);
        
        // 转发到选课列表页面
        request.getRequestDispatcher("/WEB-INF/enrollment/list.jsp").forward(request, response);
    }
    
    private void showAddForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取所有学生和课程，用于下拉选择
        List<Student> students = studentService.getStudentsByPage(1, 1000, "student_id", "ASC").getData();
        List<Course> courses = courseService.getCoursesByPage(1, 1000, "course_id", "ASC").getData();
        
        request.setAttribute("students", students);
        request.setAttribute("courses", courses);
        
        // 转发到添加页面
        request.getRequestDispatcher("/WEB-INF/enrollment/add.jsp").forward(request, response);
    }
    
    private void showEditForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取选课记录ID
        int enrollmentId = Integer.parseInt(request.getParameter("id"));
        
        // 获取选课记录信息
        Enrollment enrollment = enrollmentService.getEnrollmentById(enrollmentId);
        
        if (enrollment != null) {
            // 获取所有学生和课程，用于下拉选择
            List<Student> students = studentService.getStudentsByPage(1, 1000, "student_id", "ASC").getData();
            List<Course> courses = courseService.getCoursesByPage(1, 1000, "course_id", "ASC").getData();
            
            request.setAttribute("students", students);
            request.setAttribute("courses", courses);
            
            // 将选课记录信息存入请求属性
            request.setAttribute("enrollment", enrollment);
            
            // 转发到编辑页面
            request.getRequestDispatcher("/WEB-INF/enrollment/edit.jsp").forward(request, response);
        } else {
            // 选课记录不存在，重定向到列表页面
            response.sendRedirect(request.getContextPath() + "/WEB-INF/enrollment");
        }
    }
    
    private void addEnrollment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单数据
        int studentId = Integer.parseInt(request.getParameter("studentId"));
        int courseId = Integer.parseInt(request.getParameter("courseId"));
        String enrollmentDateStr = request.getParameter("enrollmentDate");
        String grade = request.getParameter("grade");
        
        try {
            // 解析日期
            Date enrollmentDate = dateFormat.parse(enrollmentDateStr);
            
            // 创建选课记录对象
            Enrollment enrollment = new Enrollment();
            enrollment.setStudentId(studentId);
            enrollment.setCourseId(courseId);
            enrollment.setEnrollmentDate(enrollmentDate);
            enrollment.setGrade(grade);
            
            // 添加选课记录
            boolean success = enrollmentService.addEnrollment(enrollment);
            
            if (success) {
                // 添加成功，重定向到列表页面
                response.sendRedirect(request.getContextPath() + "/WEB-INF/enrollment");
            } else {
                // 添加失败，设置错误消息
                request.setAttribute("error", "添加选课记录失败");
                
                // 重新获取学生和课程列表
                List<Student> students = studentService.getStudentsByPage(1, 1000, "student_id", "ASC").getData();
                List<Course> courses = courseService.getCoursesByPage(1, 1000, "course_id", "ASC").getData();
                
                request.setAttribute("students", students);
                request.setAttribute("courses", courses);
                
                request.getRequestDispatcher("/WEB-INF/enrollment/add.jsp").forward(request, response);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            request.setAttribute("error", "日期格式错误");
            
            // 重新获取学生和课程列表
            List<Student> students = studentService.getStudentsByPage(1, 1000, "student_id", "ASC").getData();
            List<Course> courses = courseService.getCoursesByPage(1, 1000, "course_id", "ASC").getData();
            
            request.setAttribute("students", students);
            request.setAttribute("courses", courses);
            
            request.getRequestDispatcher("/WEB-INF/enrollment/add.jsp").forward(request, response);
        }
    }
    
    private void updateEnrollment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单数据
        int enrollmentId = Integer.parseInt(request.getParameter("enrollmentId"));
        int studentId = Integer.parseInt(request.getParameter("studentId"));
        int courseId = Integer.parseInt(request.getParameter("courseId"));
        String enrollmentDateStr = request.getParameter("enrollmentDate");
        String grade = request.getParameter("grade");
        
        try {
            // 解析日期
            Date enrollmentDate = dateFormat.parse(enrollmentDateStr);
            
            // 创建选课记录对象
            Enrollment enrollment = new Enrollment();
            enrollment.setEnrollmentId(enrollmentId);
            enrollment.setStudentId(studentId);
            enrollment.setCourseId(courseId);
            enrollment.setEnrollmentDate(enrollmentDate);
            enrollment.setGrade(grade);
            
            // 更新选课记录
            boolean success = enrollmentService.updateEnrollment(enrollment);
            
            if (success) {
                // 更新成功，重定向到列表页面
                response.sendRedirect(request.getContextPath() + "/WEB-INF/enrollment");
            } else {
                // 更新失败，设置错误消息
                request.setAttribute("error", "更新选课记录失败");
                request.setAttribute("enrollment", enrollment);
                
                // 重新获取学生和课程列表
                List<Student> students = studentService.getStudentsByPage(1, 1000, "student_id", "ASC").getData();
                List<Course> courses = courseService.getCoursesByPage(1, 1000, "course_id", "ASC").getData();
                
                request.setAttribute("students", students);
                request.setAttribute("courses", courses);
                
                request.getRequestDispatcher("/WEB-INF/enrollment/edit.jsp").forward(request, response);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            request.setAttribute("error", "日期格式错误");
            
            // 重新获取学生和课程列表
            List<Student> students = studentService.getStudentsByPage(1, 1000, "student_id", "ASC").getData();
            List<Course> courses = courseService.getCoursesByPage(1, 1000, "course_id", "ASC").getData();
            
            request.setAttribute("students", students);
            request.setAttribute("courses", courses);
            
            request.getRequestDispatcher("/WEB-INF/enrollment/edit.jsp").forward(request, response);
        }
    }
    
    private void deleteEnrollment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取选课记录ID
        int enrollmentId = Integer.parseInt(request.getParameter("id"));
        
        // 删除选课记录
        boolean success = enrollmentService.deleteEnrollment(enrollmentId);
        
        // 重定向到列表页面
        response.sendRedirect(request.getContextPath() + "/WEB-INF/enrollment");
    }
}

